package com.tianxia120.website.admin.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheKit;
import com.tianxia120.website.bean.model.Article;
import com.tianxia120.website.data.entity.Result;
import com.tianxia120.website.data.utils.CommonUtils;
import com.tianxia120.website.data.utils.FieldUtils;
import com.tianxia120.website.data.utils.FileImageUtils;
import com.tianxia120.website.data.utils.ResultUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @createTime: 2018/9/21 14:45
 * @author: HingLo
 * @description: 文章管理
 */
public class ArticleService {
    private final static String CACHE_NAME = "article";

    /**
     * 通过文章的ID 来查看文章的具体内容
     *
     * @param id 文章的ID
     * @return 文章的具体的内容
     */
    public Result indexService(Long id) {
        // 默认从缓存中取出
        String body = CacheKit.get("article", id);
        if (StrUtil.isNotBlank(body)) {
            return ResultUtils.success(body);
        }
        // 如果缓存中没有,就从数据库中取出
        Article article = Article.dao.findById(id);
        if (article == null) {
            return ResultUtils.error("该文章不存在");
        }
        // 从数据库中查询文章
        body = article.getContent();
        if (StrUtil.isNotBlank(body)) {
            CacheKit.put(CACHE_NAME, id, body);
            return ResultUtils.success(body);
        }

        // 第一请求该链接,需要从下载源码与图片
        String url = article.getUrl();
        HttpRequest httpRequest = HttpRequest.get(url);
        HttpResponse httpResponse = httpRequest.execute();
        body = html(httpResponse.body());
        if (StrUtil.isNotBlank(body)) {
            CacheKit.put(CACHE_NAME, id, body);
        }
        // 将返回的body 保存到数据库中.
        Record record = new Record().set("id", id).set("content", body);
        Db.update("article", record);

        return ResultUtils.success(body);
    }

    /**
     * 解析响应的HTML,并替换文章中的图片url
     *
     * @param body 内容
     * @return 返回替换了image标签的文章内容
     */
    private String html(String body) {
        String img = "data-src";
        Document document = Jsoup.parse(body, "utf-8");
        document.body().select("img[data-src]").forEach(x -> {
            String fileName = IdUtil.simpleUUID() + ".png";
            if (download(x.attr(img), fileName)) {
                x.attr("src", CommonUtils.imgInstall(fileName, FieldUtils.IMAGE_9));
                x.removeAttr("data-src");
            }
        });
        return document.toString();
    }

    /**
     * 下载指定的图片
     *
     * @param url      图片url
     * @param fileName 文件名称
     * @return 下载结果
     */
    private boolean download(String url, String fileName) {
        HttpRequest httpRequest = HttpRequest.get(url);
        HttpResponse httpResponse = httpRequest.execute();
        byte[] img = httpResponse.bodyBytes();
        if (img == null) {
            return false;
        }
        return FileImageUtils.saveImageUtils(img, fileName, FieldUtils.IMAGE_9);
    }

    /**
     * 通过ID 删除制定的文章
     *
     * @param id id
     * @return 返回结果
     */
    public boolean deleteService(Long id) {
        // 删除文章的时候顺便删除缓存
        CacheKit.remove(CACHE_NAME, id);
        return Article.dao.deleteById(id);
    }

    /**
     * 分页查询文章
     *
     * @param page 页码
     * @param size 大小
     * @return 返回文章结果
     */
    public Map<String, Object> listService(int page, int size, int status) {
        Record record = new Record().set("status", status);
        SqlPara sql = Db.getSqlPara("website.article-list", record);
        Page<Article> list = Article.dao.paginate(page, size, sql);
        Map<String, Object> res = new TreeMap<>();
        List<Article> list1 = list.getList();
        list1.forEach(x -> {
            x.setImage(CommonUtils.imgInstall(x.getImage(), FieldUtils.IMAGE_2));
            x.setUrl(FieldUtils.URL + "/article/index?id=" + x.getId());
            if (status == 1) {
                x.remove("status");
            }
        });
        res.put("totalSize", list.getTotalRow());
        res.put("data", list1);
        return res;
    }

    /***
     * 添加文章
     * @param article 文章对象
     * @return 返回结构
     */
    public Result addService(Article article) {


        if (StrUtil.isBlank(article.getUrl())) {
            return ResultUtils.error("文章连接不能为空");
        } else {
            article.setDate(DateUtil.formatDate(new Date()));
            if (article.save()) {
                return ResultUtils.success();
            } else {
                return ResultUtils.error("添加失败");
            }
        }
    }
}
